#!/usr/bin/env bash
set -euo pipefail
set -x
# install classic notebook extensions
jupyter nbextension enable --py widgetsnbextension --sys-prefix

# ====== setup ipython conifiguration ======
mkdir -p /etc/ipython
cp /opt/jupyterlab/ipython_config.py /etc/ipython/ipython_config.py

# ====== setup juypterlab configuration overrides ======
mkdir -p /opt/conda/share/jupyter/lab/settings
cp /opt/jupyterlab/overrides.json /opt/conda/share/jupyter/lab/settings

# ====== code-server install/config
mkdir -p /opt/code_server
cd /opt/code_server
curl -fsSL https://code-server.dev/install.sh > install.sh
expected_sum=4f66ead4b4ed2be7c746f1eaf6672f3e0cddad66924d9b6c513d108d68a0127c
if [[ ! $(sha256sum install.sh) == "${expected_sum}  install.sh" ]];then
    echo Unexpected hash from code-server install script
    exit 1
fi
sh install.sh --prefix /opt/code_server

# ====== fix perms ======
fix-permissions /opt/jupyterlab /etc/ipython /opt/code_server

# if DEFAULT_ENV is unset ${DEFAULT_ENV+x} expands to nothing otherwise
# it substitutes the string x. This allows us to check if the variable
# is set without triggering an unbound variable error
if [[ -z "${DEFAULT_ENV+x}" ]]; then
    fix-permissions /opt/conda/bin
else
    fix-permissions "/opt/conda/envs/${DEFAULT_ENV}"
fi
